#!/bin/bash
# This script runs tbench for varying numbers of clients
###SHELLPACK preamble dbench-bench 65b19870

SERVER_HOST=127.0.0.1
if [ "$REMOTE_SERVER_HOST" != "" ]; then
        SERVER_HOST=$REMOTE_SERVER_HOST
fi

###SHELLPACK parseargBegin
###SHELLPACK parseargInstall
###SHELLPACK parseargParam --min-clients         TBENCH_MIN_CLIENTS
###SHELLPACK parseargParam --max-clients         TBENCH_MAX_CLIENTS
###SHELLPACK parseargEnd
###SHELLPACK monitor_hooks

install-depends popt-devel
###SHELLPACK check_install_required dbench-${VERSION}
###SHELLPACK init_complete

server_start() {
	echo Starting tbench_srv
	mmtests_activity tserver-$SERVERSIDE_NAME
	if [ "$REMOTE_SERVER_HOST" = "" ]; then
		nohup ./bin/tbench_srv 0<&- &>/dev/null &
		sleep 5
	else
		monitor_pre_hook $LOGDIR_RESULTS
		mmtests_server_ctl start --serverside-name $1
	fi
}

server_stop() {
	echo Stopping tbench_srv
	if [ "$REMOTE_SERVER_HOST" = "" ]; then
		killall -KILL tbench_srv
	else
		mmtests_server_ctl stop --serverside-name $1
		monitor_post_hook $LOGDIR_RESULTS server
	fi
}

case $SERVERSIDE_COMMAND in
start)
	server_start $SERVERSIDE_NAME
	exit $SHELLPACK_SUCCESS
	;;
stop)
	server_stop $SERVERSIDE_NAME
	exit $SHELLPACK_SUCCESS
	;;
flush)
	exit $SHELLPACK_SUCCESS
	;;
none)
	echo
	;;
*)
	die "Unrecognised server-side command"
	;;
esac

server_stop 0
###SHELLPACK threads_powertwo_begin $TBENCH_MIN_CLIENTS $TBENCH_MAX_CLIENTS
	mmtests_activity $NR_THREADS
	echo tbench run $NR_THREADS
	server_start $NR_THREADS
	monitor_pre_hook $LOGDIR_RESULTS $NR_THREADS
	./bin/tbench \
		-t $TBENCH_DURATION \
		$NR_THREADS $SERVER_HOST &> $LOGDIR_RESULTS/tbench-$NR_THREADS.log &
	TBENCH_PID=$!
	echo $TBENCH_PID > /tmp/mmtests-tbench.pid
	wait $TBENCH_PID
	RET=$?
	monitor_post_hook $LOGDIR_RESULTS $NR_THREADS
	server_stop $NR_THREADS
	gzip $LOGDIR_RESULTS/tbench-$NR_THREADS.log

	rm /tmp/mmtests-tbench.pid
	if [ $RET -ne 0 ]; then
		die "Failed to run tbench"
	fi
###SHELLPACK threads_powertwo_end

exit $SHELLPACK_SUCCESS
